package Filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

/**
 * @Author 86152
 * @create 2024/5/27 16:36
 */
@WebFilter({"/home","/home.jsp"})
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("MyFilter init");//初始化
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("MyFilter doFilter");//执行过滤逻辑
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        String username =(String) session.getAttribute("username");
        if (username==null){
            request.setAttribute("smg","请先登录!");
            request.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
        }
        System.out.println(" 2 MyFiter before doFilter");
        filterChain.doFilter(servletRequest, servletResponse);  //放行
        System.out.println(" 4 MyFilter after doFilter");

    }

    @Override
    public void destroy() {
        System.out.println("MyFilter destroy");//被注销了

    }
}
